<template>
  <!-- 从商品详情过来 -->
  <van-nav-bar
    title="购物车"
    left-text="返回"
    left-arrow
    fixed
    placeholder
    z-index="1000"
    @click-left="OnBack"
    v-if="action === 'info'"
  />

  <!-- 从底部导航栏过来 -->
  <van-nav-bar title="购物车" fixed placeholder z-index="1000" v-else />

  <!-- 列表 -->
  <van-pull-refresh v-model="refreshing" @refresh="OnRefresh">
    <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="OnLoad"
    >
      <van-checkbox-group
        v-model="CheckedArr"
        ref="CheckboxGroup"
        @change="OnToggleGroup"
      >
        <div class="cart" v-for="(item, index) in CartList" :key="item.id">
          <!-- 滑动单元格 -->
          <van-swipe-cell>
            <van-checkbox :name="item.id"></van-checkbox>
            <!-- 商品卡片 -->
            <van-card
              :thumb="item.product.thumb_text"
              @click-thumb="ToProductInfo(item.product.id)"
            >
              <template #title>
                <div class="title" @click="ToProductInfo(item.product.id)">
                  {{ item.product.name }}
                </div>
              </template>

              <!-- 卡片的插槽部分 -->
              <template #desc v-if="item.attrs">
                <van-tag
                  v-for="(attr, index) in JSON.parse(item.attrs)"
                  :key="index"
                  class="tag"
                  type="primary"
                  >{{ attr.value }}</van-tag
                >
                <van-tag class="tag" type="warning" v-if="item.type === 'live'"
                  >直播商品</van-tag
                >
              </template>

              <!-- 卡片的插槽部分 -->
              <template #desc v-else>
                <van-tag class="tag" type="danger">无商品规格</van-tag>
                <van-tag class="tag" type="warning" v-if="item.type === 'live'"
                  >直播商品</van-tag
                >
              </template>

              <template #tags>
                <div class="price">单价：￥{{ item.price }}</div>
              </template>

              <template #price>
                <div class="price">合计：￥{{ item.total }}</div>
              </template>

              <!-- 卡片的商品数量 步进器 -->
              <template #num>
                <van-stepper
                  v-model="item.nums"
                  disable-input
                  :name="index"
                  :max="
                    item.product.live_stock
                      ? item.product.live_stock
                      : item.product.stock
                  "
                  @change="OnCartUpdate"
                />
              </template>
            </van-card>

            <!-- 滑动单元格插槽 右侧滑动 -->
            <template #right>
              <van-button
                square
                text="删除"
                type="danger"
                class="delete-button"
                @click="OnDel(item.id, index)"
              />
            </template>
          </van-swipe-cell>
        </div>
      </van-checkbox-group>

      <!-- 返回顶部按钮 -->
      <van-back-top :bottom="'60'" v-if="action === 'info'" />
      <van-back-top :bottom="'100'" v-else />
    </van-list>
  </van-pull-refresh>

  <div v-if="action !== 'info'" style="height: 50px"></div>

  <!-- 提交动作栏 -->
  <van-submit-bar
    :style="action !== 'info' ? 'bottom:49px' : ''"
    :price="total"
    button-text="提交订单"
    @submit="OnSubmit"
  >
    <van-checkbox
      v-model="CheckedAll"
      :indeterminate="IsIndeterminate"
      @change="OnToggle"
      >全选</van-checkbox
    >
  </van-submit-bar>
</template>

<script setup>
// this代理
const { proxy } = getCurrentInstance();
// 用户数据
const business = proxy.$business;
// 路由跳转action
const action = ref(proxy.$route.query.action ?? "");
// 下拉刷新状态
const refreshing = ref(false); // 下拉刷新
const loading = ref(false); // 懒加载
const finished = ref(false); // 加载完成
const page = ref(1); // 分页
const CartList = ref([]); // 购物车数据
// 复选框
const CheckedArr = ref([]);
// 组件实例对象 等价于js的id
const CheckboxGroup = ref(null); // 复选
const CheckedAll = ref(false); // 全选
const IsIndeterminate = ref(false); // 不确定-

// 下拉刷新
const OnRefresh = () => {
  CartList.value = [];
  page.value = 1; // 将分页调回1
  loading.value = true; // 懒加载 true
  finished.value = false; // 加载完成 false
  refreshing.value = true; // 下拉刷新 true

  setTimeout(OnLoad, 1000);
};

// 上拉加载
const OnLoad = async () => {
  // OnRefresh过来的
  if (refreshing.value === true) {
    refreshing.value = false;
  }
  // 组装参数
  const params = {
    busid: business.value.id,
    page: page.value,
  };
  // 发起请求
  const result = await proxy.$http.post({
    url: "/cart/index",
    params,
  });
  //
  loading.value = false;
  // 处理请求结果
  if (result.code === 1) {
    let count = result.data.count;
    CartList.value = CartList.value.concat(result.data.CartData);
    if (CartList.value.length >= count) {
      finished.value = true; // 加载完成
      return;
    }
    // 分页+1
    page.value += 1;
  } else {
    finished.value = true; // 加载完成
  }
};

// 复选框事件
const OnToggleGroup = () => {
  /*  if (CartList.value.length === CheckedArr.value.length) {
    // 全选
    IsIndeterminate.value = false;
    CheckedAll.value = true;
  } else if (
    // 选中某些 但不是全选 不确定-
    CartList.value.length > CheckedArr.value.length &&
    CheckedArr.value.length > 0
  ) {
    IsIndeterminate.value = true;
    CheckedAll.value = false;
  } else {
    // 一个没选
    IsIndeterminate.value = false;
    CheckedAll.value = false;
  } */
  // 以上的简写如下：
  CheckedAll.value = CheckedArr.value.length == CartList.value.length;
  IsIndeterminate.value =
    CheckedArr.value.length > 0 &&
    CheckedArr.value.length < CartList.value.length;
};

// 增加或者减少购物车商品数量
const OnCartUpdate = async (value, { name }) => {
  // 获取当前更新购物车记录id
  const cartid = CartList.value[name].id ?? 0;
  // 组装参数
  const params = {
    busid: business.value.id,
    nums: value,
    cartid,
  };
  // 发起请求
  const result = await proxy.$http.post({
    url: "/cart/edit",
    params,
  });
  // 处理请求结果
  if (result.code === 1) {
    CartList.value[name].total = (
      parseFloat(CartList.value[name].price) * value
    ).toFixed(2);
  } else {
    proxy.$fail(result.msg);
  }
};

// 删除购物车
const OnDel = (cartid, index) => {
  // 确认框
  proxy
    .$confirm({
      title: "删除",
      message: "是否确认删除该购物车记录？",
    })
    .then(async () => {
      // 组装参数
      const params = {
        busid: business.value.id,
        cartid,
      };
      // 发起请求
      const result = await proxy.$http.post({
        url: "/cart/del",
        params,
      });
      // 处理请求结果
      if (result.code === 1) {
        proxy.$success({
          message: result.msg,
          onClose: () => {
            // 修改响应式数据，无刷新
            CartList.value.splice(index, 1);
          },
        });
      } else {
        proxy.$fail(result.msg);
      }
    })
    .catch(() => {});
};

// 全选
const OnToggle = (checked) => {
  CheckboxGroup.value.toggleAll(checked);
};

// 提交 购买
const OnSubmit = () => {
  if (CheckedArr.value.length === 0) {
    proxy.$fail("请选择结算商品");
    return;
  }
  // 获取要结算的购物车记录id
  const cartids = CheckedArr.value.join(",");
  // 跳转到结算页面
  proxy.$router.push({ path: "/cart/confirm", query: { cartids } });
};

// 底部总价 计算属性
const total = computed(() => {
  let total = 0;
  // 如果有选择商品
  if (CheckedArr.value.length > 0) {
    CartList.value.forEach((item) => {
      if (CheckedArr.value.includes(item.id)) {
        total += parseFloat(item.total);
      }
    });
  }
  // 单位：分
  return total * 100;
});

// 返回按钮
const OnBack = () => proxy.$router.back();

// 跳转到商品详情页
const ToProductInfo = (proid) =>
  proxy.$router.push({ path: "/product/info", query: { proid } });
</script>

<style scoped>
@import url("/assets/css/cart.css");
</style>